package com.asiainfo.iam.producer;

import com.alibaba.fastjson.JSON;
import com.asiainfo.iam.config.RocketMQConfig;
import com.asiainfo.iam.constant.MQConstant;
import com.asiainfo.iam.entity.dto.IncrementalSyncRequest;
import com.asiainfo.iam.entity.vo.MessageBase;
import com.asiainfo.iam.entity.vo.Organization;
import com.asiainfo.iam.entity.vo.Role;
import com.asiainfo.iam.entity.vo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
 // TODO 5
@ConditionalOnProperty(name = "enable.syn.controller", havingValue = "true")
public class IncrementalSyncProducer {
    private static final Logger log = LoggerFactory.getLogger(IncrementalSyncProducer.class);
    // RocketMQ配置
    @Autowired
    private RocketMQConfig rocketMQConfig;

    /**
     * 发送增量同步消息
     */
    public <T> void sendMessage(String objectType, T data, String operateType) throws Exception {
        // 封装消息
        MessageBase<T> msg = new MessageBase<>();
        msg.setMsgObject(objectType);
        msg.setMsgId(UUID.randomUUID().toString());
        msg.setMsgOperateType(operateType);
        msg.setMsgTime(System.currentTimeMillis());
        msg.setMsgData(data);

        String msgBody = JSON.toJSONString(msg);
        rocketMQConfig.sendIncrementalMessage(MQConstant.INCREMENTAL_SYNC_TAG, msgBody);
        log.debug("发送增量消息: 对象类型={} - 操作类型{} - 消息内容{}", objectType, operateType, msgBody);
    }

    /**
     * 增量数据发送
     */
    public void syncIncrementalData(IncrementalSyncRequest request) {
         // 从请求中获取数据
            List<Organization> newOrgs = request.getNewOrganizations();
            List<Role> newRoles = request.getNewRoles();
            List<User> newUsers = request.getNewUsers();

            List<Organization> updateOrgs = request.getUpdateOrganizations();
            List<Role> updateRoles = request.getUpdateRoles();
            List<User> updateUsers = request.getUpdateUsers();

            List<Organization> deleteOrgs = request.getDeleteOrganizations();
            List<Role> deleteRoles = request.getDeleteRoles();
            List<User> deleteUsers = request.getDeleteUsers();
            // 1. 同步新增数据（组织→角色→用户）
            syncNewData(newOrgs, newRoles, newUsers);
            // 2. 同步修改数据（用户→角色→组织）
            syncUpdateData(updateUsers, updateRoles, updateOrgs);
            // 3. 同步删除数据（用户→角色→组织）
            syncDeleteData(deleteUsers, deleteRoles, deleteOrgs);

    }
    /**
     * 同步新增数据（组织→角色→用户）
     */
    private void syncNewData(List<Organization> orgs, List<Role> roles, List<User> users) {
        if (orgs != null && !orgs.isEmpty()){
            processEntities(orgs, MQConstant.OBJECT_ORG, MQConstant.OPERATE_ADD, "新增组织");
        }
        if (roles != null && !roles.isEmpty()){
            processEntities(roles, MQConstant.OBJECT_ROLE, MQConstant.OPERATE_ADD, "新增角色");
        }
        if (users != null && !users.isEmpty()){
            processEntities(users, MQConstant.OBJECT_USER, MQConstant.OPERATE_ADD, "新增用户");
        }

    }
    /**
     * 同步修改数据（用户→角色→组织）
     */
    private void syncUpdateData(List<User> users, List<Role> roles, List<Organization> orgs) {
        if (users != null && !users.isEmpty()){
            processEntities(users, MQConstant.OBJECT_USER, MQConstant.OPERATE_UPDATE, "修改用户");
        }
        if (roles != null && !roles.isEmpty()){
            processEntities(roles, MQConstant.OBJECT_ROLE, MQConstant.OPERATE_UPDATE, "修改角色");
        }
        if (orgs != null && !orgs.isEmpty()){
            processEntities(orgs, MQConstant.OBJECT_ORG, MQConstant.OPERATE_UPDATE, "修改组织");
        }
    }

    /**
     * 同步删除数据（用户→角色→组织）
     */
    private void syncDeleteData(List<User> users, List<Role> roles, List<Organization> orgs) {
        if (users != null && !users.isEmpty()){
            processEntities(users, MQConstant.OBJECT_USER, MQConstant.OPERATE_DELETE, "删除用户");
        }
        if (roles != null && !roles.isEmpty()){
            processEntities(roles, MQConstant.OBJECT_ROLE, MQConstant.OPERATE_DELETE, "删除角色");
        }
        if (orgs != null && !orgs.isEmpty()){
            processEntities(orgs, MQConstant.OBJECT_ORG, MQConstant.OPERATE_DELETE, "删除组织");
        }

    }

    /**
     * 处理实体数据发送
     */
    private <T> void processEntities(List<T> entities, String objectType, String operateType, String logPrefix) {
        if (entities != null && !entities.isEmpty()) {
            for (T entity : entities) {
                try {
                    sendMessage(objectType, entity, operateType);
                    log.info("{}: {}", logPrefix, getEntityName(entity));
                } catch (Exception e) {
                    log.error("{} {} 失败: {}", logPrefix, objectType, e.getMessage(), e);
                    throw new RuntimeException(logPrefix + "失败", e);
                }
            }
        }
    }
    /**
     * 获取实体名称（用于日志）
     */
    private String getEntityName(Object entity) {
        if (entity instanceof Organization) {
            return ((Organization) entity).getOrgName();
        } else if (entity instanceof Role) {
            return ((Role) entity).getRoleName();
        } else if (entity instanceof User) {
            return ((User) entity).getUserName();
        }
        return "未知实体";
    }


}
